package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.model.po.CourseBase;
import com.xuecheng.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.model.dto.AddCourseDto;
import com.xuecheng.model.dto.CourseBaseInfoDto;
import com.xuecheng.model.dto.EditCourseDto;
import com.xuecheng.model.dto.QueryCourseParamsDto;
import com.xuecheng.model.po.CourseCategory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/10/8 9:46
 */
@Slf4j
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams params, QueryCourseParamsDto queryCourseParamsDto) {

        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //拼接查询条件
        //根据课程名称模糊查询  name like '%名称%'
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());

        //根据课程审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());

        //根据课程发布状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getPublishStatus());

        //分页参数
        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());

        //分页查询E page 分页参数, @Param("ew") Wrapper<T> queryWrapper 查询条件
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        //数据
        List<CourseBase> items = pageResult.getRecords();
        //总记录数
        long total = pageResult.getTotal();

        //准备返回数据 List<T> items, long counts, long page, long pageSize
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(items, total, params.getPageNo(), params.getPageSize());

        return courseBasePageResult;
    }


    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {

////        参数合法性校验
//        if (StringUtils.isBlank(addCourseDto.getName())) {
////            throw new RuntimeException("课程名称为空");
//            XueChengPlusException.cast("课程名称为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getMt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getSt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getGrade())) {
////            throw new RuntimeException("课程等级为空");
//            XueChengPlusException.cast("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
////            throw new RuntimeException("教育模式为空");
//            XueChengPlusException.cast("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getUsers())) {
////            throw new RuntimeException("适应人群为空");
//            XueChengPlusException.cast("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getCharge())) {
////            throw new RuntimeException("收费规则为空");
//            XueChengPlusException.cast("收费规则为空");
//        }
        //向课程基本信息表course_base写数据
        CourseBase courseBaseNew = new CourseBase();
//        courseBaseNew.setName(addCourseDto.getName());
//        courseBaseNew.setMt(addCourseDto.getMt());
//        courseBaseNew.setSt(addCourseDto.getSt());
//        上面这种从get里面拿东西放到set里面去，这种方法很复杂
        BeanUtils.copyProperties(addCourseDto,courseBaseNew);
        courseBaseNew.setCompanyId(companyId);
        courseBaseNew.setCreateDate(LocalDateTime.now());
//        默认为未提交
        courseBaseNew.setAuditStatus("202002");
//        发布状态未提交
        courseBaseNew.setAuditStatus("203001");
//        插入数据库
        int insert = courseBaseMapper.insert(courseBaseNew);
//        判断是否插入成功
        if(insert <= 0){
            throw new RuntimeException("添加课程失败");
        }

        //向课程营销表courese_market写入数据
        CourseMarket courseMarket = new CourseMarket();
//        获取课程ID
        Long courseId = courseBaseNew.getId();
        courseMarket.setId(courseId);
//        保存营销信息
        saveCourseMarket(courseMarket);
//        从数据库查询课程的详细信息，包括两部分
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

//    单独写一个方法保存营销信息，逻辑：存在则更新，不存在则添加
    private int saveCourseMarket(CourseMarket courseMarketNew){
//       参数合法性校验
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isEmpty(charge)){
            throw new RuntimeException("收费规则为空");
        }
//        如果课程收费，价格没有填写也需要抛出异常
        if (charge.equals("201001")) {
            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice() <= 0) {
                throw new RuntimeException("课程的价格不能为空且必须大于0");
            }
        }
//        从数据库查询营销信息，存在则更新，不存在则添加
        Long id = courseMarketNew.getId();
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if(courseMarket == null){
//            插入数据库
            int insert = courseMarketMapper.insert(courseMarketNew);
            return insert;
        }else {
//            更新
            BeanUtils.copyProperties(courseMarketNew,courseMarket);
            courseMarket.setId(courseMarketNew.getId());
            int i = courseMarketMapper.updateById(courseMarket);
            return i;
        }
    }

//    @Transactional
//    @Override
//    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
//        //对参数进行合法性的校验
//        //合法性校验
//        if (StringUtils.isBlank(dto.getName())) {
//            throw new RuntimeException("课程名称为空");
//        }
//
//        if (StringUtils.isBlank(dto.getMt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
//        }
//         //对数据进行封装，调用mapper进行数据持久化
//        CourseBase courseBase = new CourseBase();
//        //将传入dto的数据设置到 courseBase对象
////        courseBase.setName(dto.getName());
////        courseBase.setMt(dto.getMt());
////        courseBase.setSt(dto.getSt());
//        //将dto中和courseBase属性名一样的属性值拷贝到courseBase
//        BeanUtils.copyProperties(dto,courseBase);
//        //设置机构id
//        courseBase.setCompanyId(companyId);
//        //创建时间
//        courseBase.setCreateDate(LocalDateTime.now());
//        //审核状态默认为未提交
//        courseBase.setAuditStatus("202002");
//        //发布状态默认为未发布
//        courseBase.setStatus("203001");
//        //课程基本表插入一条记录
//        int insert = courseBaseMapper.insert(courseBase);
//        //获取课程id
//        Long courseId = courseBase.getId();
//        CourseMarket courseMarket = new CourseMarket();
//        //将dto中和courseMarket属性名一样的属性值拷贝到courseMarket
//        BeanUtils.copyProperties(dto,courseMarket);
//        courseMarket.setId(courseId);
//        //校验如果课程为收费，价格必须输入
//        String charge = dto.getCharge();
//        if(charge.equals("201001")){//收费
//            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue()<=0){
//                throw new RuntimeException("课程为收费但是价格为空");
//            }
//        }
//
//        //向课程营销表插入一条记录
//        int insert1 = courseMarketMapper.insert(courseMarket);
//
//        if(insert<=0|| insert1<=0){
//            throw new RuntimeException("添加课程失败");
//        }
//
//        //组装要返回的结果
//        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
//        return courseBaseInfo;
//    }

    /**
     * 根据课程id查询课程的基本和营销信息
     * @param courseId 课程id
     * @return 课程的信息
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        //基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }

        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        if(courseMarket != null){
            BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //根据课程分类的id查询分类的名称
        String mt = courseBase.getMt();
        String st = courseBase.getSt();

        CourseCategory mtCategory = courseCategoryMapper.selectById(mt);
        CourseCategory stCategory = courseCategoryMapper.selectById(st);
        if(mtCategory!=null){
            //分类名称
            String mtName = mtCategory.getName();
            courseBaseInfoDto.setMtName(mtName);
        }
        if(stCategory!=null){
            //分类名称
            String stName = stCategory.getName();
            courseBaseInfoDto.setStName(stName);
        }
        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto courseDto){
        //获取课程id
        Long courseId = courseDto.getId();
//        查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            XueChengPlusException.cast("课程不存在");
        }
        //数据合法校验
        //根据具体的业务逻辑去校验
        //本机构只能修改本机构的课程
        if(!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("只能修改本机构的课程");
        }
//        封装数据
        BeanUtils.copyProperties(courseDto,courseBase);
//        修改时间
        courseBase.setChangeDate(LocalDateTime.now());
//        更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if(i < 0){
            XueChengPlusException.cast("更新失败");
        }

//        更新营销信息
        CourseMarket courseMarket = new CourseMarket();
        courseMarket.setId(courseId);
        courseMarket.setQq(courseDto.getQq());
        courseMarket.setPhone(courseDto.getPhone());
        courseMarket.setPrice(courseDto.getPrice());
        courseMarket.setCharge(courseDto.getCharge());
        courseMarket.setWechat(courseDto.getWechat());
        courseMarket.setOriginalPrice(courseDto.getOriginalPrice());
        courseMarket.setValidDays(courseDto.getValidDays());
        int i1 = saveCourseMarket(courseMarket);
        if(i1 < 0){
            XueChengPlusException.cast("更新营销表失败");
        }

        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }


}